package com.wangzhen.codebase.apidemo;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo<K, V> {

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private final Map<K, V> map = new HashMap<>();

    public V get(K k) {
        Lock readLock = readWriteLock.readLock();
        try {
            readLock.lock();
            V v = map.get(k);
            return v;
        } finally {
            readLock.unlock();
        }
    }
    public synchronized V sget(K k) {
            V v = map.get(k);
            return v;
    }

    public void put(K k, V v) {
        Lock writeLock = readWriteLock.writeLock();
        try {
            writeLock.lock();
            map.put(k, v);
        } finally {
            writeLock.unlock();
        }
    }

    static class MyThread extends Thread{
        private CountDownLatch latch;
        private ReadWriteLockDemo demo;
        public MyThread(CountDownLatch latch, ReadWriteLockDemo demo) {
            this.latch = latch;
            this.demo = demo;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100_000; i++) {
                demo.get("china");
            }
            latch.countDown();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        long startMillis = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(100);
        ReadWriteLockDemo<String, String> demo = new ReadWriteLockDemo();
        demo.put("china", "中国");
        for (int i = 0; i < 100; i++) {
            Thread thread = new MyThread(latch, demo);
            thread.start();
        }
        latch.await();

        long endMillis = System.currentTimeMillis();
        System.out.println("end:" + (endMillis-startMillis) + "ms");
    }


}
